/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
*/

package org.elephantt.webby;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.lang.reflect.Method;

/**
 * A request mapper that supports parameterized URL path expression mappings of the following form:
 *  /person/:username
 *  /wiki/:language/:title
 *  etc.
 *
 * Similar to Ruby on Rails routes mapping.
 */
public class RouteRequestMapper implements RequestMapper {
  private List<ControllerMapping> mappings = new LinkedList<ControllerMapping>();
  private Map<ControllerMapping, String[]> pathPartMap = new HashMap<ControllerMapping, String[]>();

  private final Class requestClass;
  private final Class responseClass;
  private final String specialPostValue = "new";

  /**
   * Creates a new mapper given the request and response classes that are being used.
   * @param requestClass
   * @param responseClass
   */
  public RouteRequestMapper(Class requestClass, Class responseClass) {
    this.requestClass = requestClass;
    this.responseClass = responseClass;
  }

  public RouteRequestMapper() {
    this(Request.class, Response.class);
  }

  private String computeMethodName(String methodName, HttpMethod httpMethod) {
    String effectiveMethodName = methodName;
    if (methodName == null) {
      if (httpMethod != null) {
        String httpMethodString = httpMethod.toString();
        effectiveMethodName = "handle" + httpMethodString.substring(0, 1) + httpMethodString.substring(1).toLowerCase();
      } else {
        effectiveMethodName = "handle";
      }
    }
    return effectiveMethodName;
  }

  private void addRoute(ControllerMapping controllerMapping) {
    mappings.add(controllerMapping);
    pathPartMap.put(controllerMapping, UrlUtil.tokenizePath(controllerMapping.getPathExpression()));
  }

  /**
   * Maps a request route to a controller and methdod
   * @param httpMethod The HTTP method to match on. null specifies that we should match on all methods.
   * @param pathExpression The URI path expression to match on, such as "/person/:urlname"
   * @param controller The controller instance that will handle the request
   * @param requestHandlerMethodName The method name of the controller that will handle the request. Must be a method
   *  having an acceptable signature.
   * @throws WebbyException if the route is unacceptable in any way.
   */
  public void addRoute(HttpMethod httpMethod, String pathExpression, Object controller, String requestHandlerMethodName) {
    String effectiveMethodName = computeMethodName(requestHandlerMethodName, httpMethod);
    Method effectiveMethod = chooseEffectiveMethod(effectiveMethodName, controller);
    if (effectiveMethod == null) {
      throw new WebbyException("Missing method for mapping '" + pathExpression + "': '" + effectiveMethodName + "' on " + controller.getClass());
    }
    addRoute(new ControllerMapping(pathExpression, httpMethod, controller, effectiveMethod));
  }

  private void addRouteForMethod(HttpMethod httpMethod, String pathExpression, Object controller) {
    Method method = chooseEffectiveMethod(httpMethod.toString().toLowerCase(), controller);
    if (method != null) {
      addRoute(new ControllerMapping(pathExpression, httpMethod, controller, method));
    }
  }

  /**
   * Warning: this is experimental. I'm not sure I like it yet.
   *
   * TODO: There is one bug:
   *
   * GET /person/new will work. It should return BAD METHOD.
   *
   * TODO: let the special value 'new' be configurable
   *
   * @param pathExpression
   * @param controller
   */
  public void addResourceRoute(String pathExpression, Object controller, String replaceParameter) {
    addRouteForMethod(HttpMethod.GET, pathExpression, controller);
    addRouteForMethod(HttpMethod.PUT, pathExpression, controller);
    addRouteForMethod(HttpMethod.DELETE, pathExpression, controller);
    addRouteForMethod(HttpMethod.CONNECT, pathExpression, controller);
    addRouteForMethod(HttpMethod.HEAD, pathExpression, controller);
    addRouteForMethod(HttpMethod.OPTIONS, pathExpression, controller);
    addRouteForMethod(HttpMethod.TRACE, pathExpression, controller);

    // POST is handled specially
    addRouteForMethod(HttpMethod.POST, pathExpression.replaceAll(":" + replaceParameter, specialPostValue), controller);
  }

  /**
   * Chooses the controller method that we will dispatch to. There are several different signatures we
   * support.
   *
   * @param effectiveMethodName  The method name we're looking for.
   * @param controller  The controller we're going to look for the method on.
   * @return  The controller method, if one exists.
   * @throws WebbyException If we matched more than one possible controller method. This indicates a programmer error.
   */
  private Method chooseEffectiveMethod(String effectiveMethodName, Object controller) {
    Method[] methods = new Method[3];
    methods[0] = lookupMethod(controller, effectiveMethodName, requestClass, responseClass);
    methods[1] = lookupMethod(controller, effectiveMethodName, requestClass);
    methods[2] = lookupMethod(controller, effectiveMethodName);

    Method effectiveMethod = null;

    int methodCount = 0;
    for (Method m : methods) {
      if (m != null) {
        if (++methodCount > 1) {
          throw new WebbyException("More than one matching method was found for controller " + controller + " and method '" + effectiveMethodName + "'. You can only have one method of the form 'public [void|type] "+ effectiveMethodName + "(Request request, Response response)', 'public [void|type] " + effectiveMethodName + "(Request request)', and 'public [void|type] " + effectiveMethodName + "()'");
        }
        effectiveMethod = m;
      }
    }

    return effectiveMethod;
  }

  /**
   * Same as object.getClass().getMethod(), but returns null if no method is found instead of throwing an exception.
   */
  private Method lookupMethod(Object object, String method, Class... parameters) {
    try {
      return object.getClass().getMethod(method, parameters);
    } catch (NoSuchMethodException e) {
      return null;
    }
  }

  /**
   * Returns the request mapping for the given request. If no mapping is found, null is returned.
   * @param request
   * @return
   */
  public RequestMapping map(HttpServletRequest request) {
    String uri = request.getRequestURI();
    String[] requestPathParts = UrlUtil.tokenizePath(uri);

    RequestMapping rv = null;
    Iterator<ControllerMapping> i = mappings.iterator();
    String httpMethod = request.getMethod();

    while (rv == null && i.hasNext()) {
      rv = match(httpMethod, requestPathParts, i.next());
    }

    return rv;
  }

  private RequestMapping match(String httpMethod, String[] requestPathParts, ControllerMapping controllerMapping) {
    if (controllerMapping.getHttpMethod() != null && !controllerMapping.getHttpMethod().toString().equals(httpMethod)) {
      return null;
    }

    String[] mappingPathParts = pathPartMap.get(controllerMapping);

    if (isPathPartsMatch(requestPathParts, mappingPathParts)) {
      return new RequestMapping(controllerMapping.getRequestHandler(), controllerMapping.getRequestHandlerMethod(), controllerMapping.getViewNamePrefix(), createPathPartMap(requestPathParts, mappingPathParts));
    } else {
      return null;
    }
  }

  private Map<String, String> createPathPartMap(String[] requestPathParts, String[] mappingPathParts) {
    Map<String, String> map = new HashMap<String, String>();
    for (int i = 0; i < mappingPathParts.length; i++) {
      if (mappingPathParts[i].startsWith(":")) {
        map.put(mappingPathParts[i].substring(1), requestPathParts[i]);
      }
    }
    return map;
  }

  /**
   * @return true iff the request path parts match the mapping path parts.
   */
  private boolean isPathPartsMatch(String[] requestPathParts, String[] mappingPathParts) {
    boolean pathPartsMatch = true;
    if (requestPathParts.length == mappingPathParts.length) {
      for (int i = 0; i < requestPathParts.length && pathPartsMatch; i++) {
        if (!isPartMatch(requestPathParts[i], mappingPathParts[i])) {
          pathPartsMatch = false;
        }
      }
    } else {
      pathPartsMatch = false;
    }
    return pathPartsMatch;
  }

  /**
   * @return true iff the request path part match the mapping path part.
   */
  private boolean isPartMatch(String requestPart, String mappingPart) {
    return requestPart.equals(mappingPart) || (mappingPart.startsWith(":") && !requestPart.equals(specialPostValue));
  }

  /**
   * A mapping between a URL path expression and the request handler that should handle
   * that set of URLs
   *
   * TODO: consider making this a top-level class, and have RequestMapping contain it. Right now, RequestMapping and ControllerMapping
   * duplicate fields that we copy needlessly.
   */
  private static class ControllerMapping {
    private final String pathExpression;
    private final HttpMethod httpMethod; // nullable
    private final Object requestHandler;
    private final Method requestHandlerMethod;
    private final String viewNamePrefix;

    public ControllerMapping(String pathExpression, HttpMethod httpMethod, Object requestHandler, Method requestHandlerMethod) {
      if (pathExpression == null) throw new IllegalArgumentException();
      if (requestHandler == null) throw new IllegalArgumentException();

      this.pathExpression = pathExpression;
      this.httpMethod = httpMethod;
      this.requestHandler = requestHandler;
      this.requestHandlerMethod = requestHandlerMethod;

      // TODO: this is a prototype implementation... needs to be more robust.
      String controller = requestHandler.getClass().getSimpleName().replace("Controller", "").toLowerCase();
      String method = requestHandlerMethod.getName().toLowerCase();
      viewNamePrefix = controller + "_" + method;
    }

    public String getPathExpression() {
      return pathExpression;
    }

    public HttpMethod getHttpMethod() {
      return httpMethod;
    }

    public Object getRequestHandler() {
      return requestHandler;
    }

    public Method getRequestHandlerMethod() {
      return requestHandlerMethod;
    }

    public String getViewNamePrefix() {
      return viewNamePrefix;
    }
  }
}